package model

import (
	"errors"
	"server/share/config"

	"github.com/hwcer/cosgo/schema"
	"github.com/hwcer/updater"
	"github.com/hwcer/updater/dataset"
	"github.com/hwcer/updater/operator"
)

func init() {
	Register(&Teams{})
}

func NewTeams(u *updater.Updater, iid int32, val int64) *Teams {
	i := &Teams{}
	i.Init(u, iid)
	i.OID = Unique(u, iid)
	i.Value = make(map[string]string)
	return i
}

// Teams 阵容信息
type Teams struct {
	Model  `bson:"inline"`
	Name   string            `json:"name,omitempty" bson:"name"`
	Value  map[string]string `json:"value" bson:"value"`
	Talent []int32           `json:"talent,omitempty" bson:"talent"` //使用的天赋GROUP
}

func (this *Teams) Get(k string) (any, bool) {
	switch k {
	case "Name", "name":
		return this.Name, true
	case "Value", "value":
		return this.Value, true
	default:
		return this.Model.Get(k)
	}
}

// Set 更新器
func (this *Teams) Set(k string, v any) (any, bool) {
	switch k {
	case "Name", "name":
		this.Name = v.(string)
	case "Value", "value":
		this.Value = v.(map[string]string)
	default:
		return this.Model.Set(k, v)
	}
	return v, true
}

func (this *Teams) Clone() *Teams {
	r := *this
	r.Value = make(map[string]string)
	for k, v := range this.Value {
		r.Value[k] = v
	}
	return &r
}

func (this *Teams) IType(int32) int32 {
	return config.ITypeTeams
}

// ----------------- 作为MODEL方法--------------------
func (this *Teams) Schema() *schema.Schema {
	sch, _ := schema.Parse(this)
	return sch
}
func (this *Teams) Upsert(u *updater.Updater, op *operator.Operator) bool {
	return true
}

func (this *Teams) Getter(u *updater.Updater, coll *dataset.Collection, keys []string) error {
	uid := u.Uid()
	if uid == "" {
		return errors.New("Shop.Getter uid not found")
	}
	tx := db.Where("uid = ?", uid)
	if len(keys) > 0 {
		tx = tx.Where("_id IN ?", keys)
	}
	var rows []*Teams
	if tx = tx.Find(&rows); tx.Error != nil {
		return tx.Error
	}
	for _, v := range rows {
		coll.Receive(v.OID, v)
	}
	return nil
}

func (this *Teams) Setter(u *updater.Updater, bulkWrite dataset.BulkWrite) error {
	return bulkWrite.Submit()
}

func (this *Teams) BulkWrite(u *updater.Updater) dataset.BulkWrite {
	return NewBulkWrite(this)
}
